package com.ai.web.weixin.processor;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ai.web.cache.Constants;
import com.ai.web.sendreq.ICachUtil;
import com.ai.web.service.ICashDeviceService;
import com.ai.web.service.QrcodeService;
import com.ai.web.service.WxUserService;
import com.ai.web.util.Utils;
import com.ai.web.vo.ICashDeviceV;
import com.ai.web.vo.ICashSerialNumReturnMsgV;
import com.ai.web.vo.QrcodeV;
import com.ai.web.vo.ResultModel;
import com.ai.web.weixin.message.request.ReqBaseMessage;
import com.ai.web.weixin.message.request.ScanMessage;
import com.ai.web.weixin.message.response.Article;
import com.ai.web.weixin.message.response.NewsMessage;
import com.ai.web.weixin.message.response.TextMessage;
import com.ai.web.weixin.message.util.MessageUtil;
import com.tiny.persistence.domain.WxRoleMenu;
import com.tiny.persistence.domain.WxUser;
import com.tiny.persistence.repository.WxRoleMenuRepo;

@Service(value = "scanMsgProcessor")
public class ScanMsgProcessor implements IMessageProcessor {

	private static Logger logger = Logger.getLogger(ScanMsgProcessor.class);
	@Autowired
	private WxUserService wxUserService;
	@Autowired
	private WxRoleMenuRepo wxRoleMenuRepo;
	@Autowired
	private QrcodeService qrcodeService;
	@Autowired
	private ICashDeviceService iCashDeviceService;
	
	public String process(ReqBaseMessage bm) {

		logger.info("[Click Processor] " + bm.toString());

		ScanMessage sm = (ScanMessage) bm;
		String eventKey = sm.getEventKey();
		logger.info("[Scan eventKey] " + eventKey);
		// 根据openId首先需要判断权限，看有没有权限报修，跟菜单点击那个判断一样
		WxUser user = wxUserService.getByOpenId(bm.getFromUserName());
		if (user == null) {
			String content = "您好,您还没有关注，不能报修！";
			// 回复文本消息
			com.ai.web.weixin.message.response.TextMessage textMessage = new com.ai.web.weixin.message.response.TextMessage();
			textMessage.setToUserName(bm.getFromUserName());
			textMessage.setFromUserName(bm.getToUserName());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setContent(content);
			return MessageUtil.textMessageToXml(textMessage);
		}
		List<WxRoleMenu> list = wxRoleMenuRepo.getByKeyword(user.getWxRole()
				.getId(), "repair");
		logger.info("[Click WxRoleMenu] " + list);
		if (list == null || list.size() == 0) {
			TextMessage nm = new TextMessage();
			nm.setToUserName(bm.getFromUserName());
			nm.setFromUserName(bm.getToUserName());
			nm.setCreateTime(System.currentTimeMillis());
			nm.setMsgType(MessageUtil.REQ_MESSAGE_TYPE_TEXT);
			nm.setContent("对不起,您没有操作该功能的权限!");
			return MessageUtil.textMessageToXml(nm);
		}
		// 验证序列号
		QrcodeV qrcode = null;
		boolean flag = false;
		try {
			qrcode = qrcodeService.getQrcode(Integer.valueOf(eventKey));
		} catch (Exception e) {
			e.printStackTrace();
			flag = true;
		}
		logger.info("qrcode:" + qrcode);
		if (flag || qrcode == null || Utils.isEmpty(qrcode.getSerialNumber())) {
			String content = "您好,获取序列号失败！";
			// 回复文本消息
			com.ai.web.weixin.message.response.TextMessage textMessage = new com.ai.web.weixin.message.response.TextMessage();
			textMessage.setToUserName(bm.getFromUserName());
			textMessage.setFromUserName(bm.getToUserName());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setContent(content);
			return MessageUtil.textMessageToXml(textMessage);
		}
		String serialNumber = qrcode.getSerialNumber();
		ICashSerialNumReturnMsgV iCashSerialNumReturnMsgV = ICachUtil
				.verificationSerialNumber(serialNumber);
		if (iCashSerialNumReturnMsgV.getResult() == 0) {
			logger.info("Verification error:"
					+ iCashSerialNumReturnMsgV.getErrorMsg());
			// 回复文本消息
			com.ai.web.weixin.message.response.TextMessage textMessage = new com.ai.web.weixin.message.response.TextMessage();
			textMessage.setToUserName(bm.getFromUserName());
			textMessage.setFromUserName(bm.getToUserName());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setContent(iCashSerialNumReturnMsgV.getErrorMsg());
			return MessageUtil.textMessageToXml(textMessage);
		}
		NewsMessage nm = new NewsMessage();
		nm.setToUserName(bm.getFromUserName());
		nm.setFromUserName(bm.getToUserName());
		nm.setCreateTime(System.currentTimeMillis());
		nm.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);

		List<Article> articles = new ArrayList<Article>();
		Article article = new Article();
		article.setTitle("报修");
		article.setDescription("点击进入报修页面");
		article.setPicUrl(Constants.SERVER_HOST + "/images/wx/1400126728133.jpg");
		ICashDeviceV iCashDeviceV = new ICashDeviceV();
		iCashDeviceV.setSerialNumber(serialNumber);
		iCashDeviceV.setContact(iCashSerialNumReturnMsgV.getContact());
		iCashDeviceV.setContactPhone(iCashSerialNumReturnMsgV.getContactPhone());
		iCashDeviceV.setManufacturer(iCashSerialNumReturnMsgV.getManufacturerV().getBrandName());
		iCashDeviceV.setMaintenanceUser(iCashSerialNumReturnMsgV.getMaintenanceUser());
		iCashDeviceV.setMaintenancePhone(iCashSerialNumReturnMsgV.getMaintenancePhone());
		iCashDeviceV.setModel(iCashSerialNumReturnMsgV.getModelV().getModelName());
		iCashDeviceV.setMachineAddress(iCashSerialNumReturnMsgV.getManufacturerV().getFactAddress());
		iCashDeviceV.setOrgId(iCashSerialNumReturnMsgV.getOrgId());
		iCashDeviceV.setOrgName(iCashSerialNumReturnMsgV.getOrgName());
		try {
			ResultModel result = iCashDeviceService.save(iCashDeviceV);
			logger.info("iCashDeviceService result:" + result);
			if(result.getStatusCode() != 20011011){
				String content = "您好,获取设备信息失败！";
				// 回复文本消息
				com.ai.web.weixin.message.response.TextMessage textMessage = new com.ai.web.weixin.message.response.TextMessage();
				textMessage.setToUserName(bm.getFromUserName());
				textMessage.setFromUserName(bm.getToUserName());
				textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
				textMessage.setContent(content);
				return MessageUtil.textMessageToXml(textMessage);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String url = Constants.SERVER_HOST + "/weixin/repair/add/" + serialNumber
				+ "?openId=" + bm.getFromUserName();
		logger.info("[Scan url] " + url);
		article.setUrl(url);
		articles.add(article);
		nm.setArticleCount(articles.size());
		nm.setArticles(articles);
		return MessageUtil.newsMessageToXml(nm);
	}

}
